package com.feihong.txgw.ui.activity.kaika;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.feihong.txgw.R;
import com.feihong.txgw.inter.contract.kaika.ISubscribeKaikaContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.kaika.KaikaYuYueOrderInfo;
import com.feihong.txgw.model.bean.kaika.YuyueViewShowEnity;
import com.feihong.txgw.tx_precenter.SubscribeKaikaMainPrecenter;
import com.feihong.txgw.ui.activity.order.PayActivity;
import com.feihong.txgw.ui.activity.order.PaySuccessActivity;
import com.feihong.txgw.ui.activity.user.MyDeliveryAdrActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.PreferenceTools;
import com.feihong.txgw.utils.kaika.KaikaIntentType;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.ui.activity.kaika
 * @class describe: 无卡开户 预约开户
 * @time 2017/9/18 18:03
 * @change
 * @chang time
 * @class describe
 */
public class KaikaNoCardOperateActivity extends BaseMVPCompateActivity<ISubscribeKaikaContract.AbSubscribeKaikaPrecenter> implements ISubscribeKaikaContract.ISubscribeKaikaMainView, View.OnClickListener {
    @BindView(R.id.kaika_no_card_select_adr)
    RelativeLayout mSelectAdrLayout;
    @BindView(R.id.kaika_no_card_select_phoneNum)
    RelativeLayout mSelectPhoneNumLayout;
    @BindView(R.id.kaika_no_card_select_package)
    RelativeLayout mSelectPackageLayout;
    @BindView(R.id.kaika_no_card_adr_tv)
    TextView mSelectAdr;
    @BindView(R.id.kaika_no_card_phoneNum_tv)
    TextView mSelectPhoneNum;
    @BindView(R.id.kaika_no_card_package_tv)
    TextView mSelectPackage;
    @BindView(R.id.kaika_no_card_submit_tv)
    TextView mSubmit;
    @BindView(R.id.kaika_toDoor_img_btn)
    ImageView mToDoorService;
    @BindView(R.id.kaika_jika_img_btn)
    ImageView mJiKaService;
    private boolean isToDoorService = false;
    private Drawable mSelect, mUnSelect;

    private static final int SELECT_PHONENUM_REQUEST_CODE = 8;
    private static final int SELECT_PACKAGE_REQUEST_CODE = 9;

    private KaikaYuYueOrderInfo mKaikaYuYueOrderInfo;

    @Override
    public void setTheme() {
    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_kaika_no_card_layout;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setPageTitle("预约开户");
        setBackButtonFinish();
        mKaikaYuYueOrderInfo = KaikaYuYueOrderInfo.getInstance();
        mSelect = getResources().getDrawable(R.mipmap.delivery_adr_sex_select);
        mUnSelect = getResources().getDrawable(R.mipmap.delivery_adr_sex_unselect);
        mToDoorService.setImageDrawable(mUnSelect);
        mJiKaService.setImageDrawable(mSelect);
        Bundle bundle = getIntent().getExtras();
        mPresenter.parseIntentAndGetDefAdr(bundle);
    }

    @Override
    public void bindData() {
        mSelectAdrLayout.setOnClickListener(this);
        mSelectPhoneNumLayout.setOnClickListener(this);
        mSelectPackageLayout.setOnClickListener(this);
        mSubmit.setOnClickListener(this);
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void onClick(View view) {
        Intent mIntent;
        switch (view.getId()) {
            case R.id.kaika_no_card_select_adr:
                mIntent = new Intent(this, MyDeliveryAdrActivity.class);
                if (TextUtils.isEmpty(mKaikaYuYueOrderInfo.getmPackageInfo())) {
                    mIntent.putExtra(KaikaIntentType.ADRESS_INTENT_TYPE_KEY, KaikaIntentType.ADDRESS_INTENT_TYPE_ITEM_CLICK_NEXT_PACKAGE);
                    startActivity(mIntent);
                } else {
                    mIntent.putExtra(KaikaIntentType.ADRESS_INTENT_TYPE_KEY, KaikaIntentType.ADDRESS_INTENT_TYPE_ITEN_CLICK_BACK);
                    startActivityForResult(mIntent, MyDeliveryAdrActivity.ADR_ITEMCLICK_REQUEST_CODE);
                    getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                }
                break;
            case R.id.kaika_no_card_select_package:
                mIntent = new Intent(this, KaikaNewPackageActivity.class);
                mIntent.putExtra(KaikaIntentType.PACKAGE_INTENT_TYPE_KEY, KaikaIntentType.INTENT_FROM_YUYUE_PAGE);
                startActivityForResult(mIntent, SELECT_PACKAGE_REQUEST_CODE);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.kaika_no_card_select_phoneNum:
                if (TextUtils.isEmpty(mKaikaYuYueOrderInfo.getmPackageInfo())) {
                    showSystemToast("请先选择套餐");
                    return;
                }
                mIntent = new Intent(this, KaiKaStep2Activity.class);
                mIntent.putExtra(KaikaIntentType.PHONE_NUMBER_INTENT_TYPE_KEY, KaikaIntentType.INTENT_FROM_YUYUE_PAGE);
                mIntent.putExtra(KaikaIntentType.SELECT_PACKAGE_ID_KEY, mKaikaYuYueOrderInfo.getmPackageId());
                startActivityForResult(mIntent, SELECT_PHONENUM_REQUEST_CODE);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.kaika_no_card_submit_tv:
                if (TextUtils.isEmpty(mKaikaYuYueOrderInfo.getmAddress())) {
                    showSystemToast("请选择收货地址");
                    return;
                } else if (TextUtils.isEmpty(mKaikaYuYueOrderInfo.getmPackageInfo())) {
                    showSystemToast("请选择套餐");
                    return;
                } else if (TextUtils.isEmpty(mKaikaYuYueOrderInfo.getmPhoneNum())) {
                    showSystemToast("请选择手机号");
                    return;
                }
                submitOrder();
                break;
            case R.id.kaika_jika_btn_layout:
                isToDoorService = !isToDoorService;
                mJiKaService.setImageDrawable(mSelect);
                mToDoorService.setImageDrawable(mUnSelect);
                break;
            case R.id.kaika_ziti_btn_layout:
                isToDoorService = !isToDoorService;
                mJiKaService.setImageDrawable(mUnSelect);
                mToDoorService.setImageDrawable(mSelect);
                break;
            default:
                break;
        }
    }

    private void submitOrder() {
        String serviceType = "";
        if (isToDoorService) {
            serviceType = "2";
        } else {
            serviceType = "1";
        }
        showProgressDialog("正在提交订单...");
        mPresenter.submitOrder(mKaikaYuYueOrderInfo.getmPackageId(), mKaikaYuYueOrderInfo.getmPhoneNum(), mKaikaYuYueOrderInfo.getmAddressId(), serviceType);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mKaikaYuYueOrderInfo = KaikaYuYueOrderInfo.getInstance();
        KaikaManager.getmKaikaManager().clearAll();
        mSelectPackage.setText(TextUtils.isEmpty(mKaikaYuYueOrderInfo.getmPackageInfo()) ? "选择套餐" : mKaikaYuYueOrderInfo.getmPackageInfo());
        mSelectPhoneNum.setText(TextUtils.isEmpty(mKaikaYuYueOrderInfo.getmPhoneNum()) ? "选择号码" : mKaikaYuYueOrderInfo.getmPhoneNum());
        mPresenter.getNewAdr();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: 清楚 ");
        PreferenceTools.putString(MyDeliveryAdrActivity.SELECT_ADR_KEY, "");
        mKaikaYuYueOrderInfo.setmAddressId(null);
        mKaikaYuYueOrderInfo.setmAddress(null);
        mKaikaYuYueOrderInfo.setmPhoneNum(null);
        mKaikaYuYueOrderInfo.setmPackageId(null);
        mKaikaYuYueOrderInfo.setmPackageInfo(null);
    }

    /**
     * 待整合
     * @param result
     */
    @Override
    public void submitOrderResult(String result) {
        try {
            final JSONObject jsonObject = new JSONObject(result);
            String resultCode = jsonObject.optString("code");
            if ("200".equals(resultCode)) {
                showDialog(null, "订单提交成功", new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        JSONObject orderObj = jsonObject.optJSONObject("data");
                        Intent intent = new Intent(KaikaNoCardOperateActivity.this, PayActivity.class);
                        intent.putExtra(PayActivity.INTENT_PAY_TYPE, PayActivity.PAY_TYPE_KAIKA);
                        intent.putExtra(PayActivity.INTENT_ORDER_ID, orderObj.optString("order_sn"));
                        intent.putExtra(PayActivity.INTENT_TITLE, orderObj.optString("body"));
                        startActivity(intent);
                        finish();
                    }
                });
            } else if ("300".equals(resultCode)) {
                Intent intent = new Intent();
                intent.setClass(KaikaNoCardOperateActivity.this, PaySuccessActivity.class);
                intent.putExtra(PaySuccessActivity.INTENT_TYPE, PaySuccessActivity.TYPE_SUBMIT_SUCCESS);
                startActivity(intent);
                finish();
            } else {
                showDialog("错误", "提交失败：\n" + jsonObject.optString("msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 此方法分为两种情况
     * 1)从首页选择套餐/手机号码之后 跳转而来  此时的yuyueViewShowEnity 会携带套餐信息/手机号码/用户地址信息(如果用户有创建过地址的话)
     * 2)从首页选择更多套餐进入 然后选择套餐 选择号码 之后跳转而来  此时的yuyueViewShowEnity只含有用户地址信息(如果用户有创建过地址的话)
     *
     * 关于收货地址
     *      如果用户通过此界面手动选择了地址 那么mKaikaYuYueOrderInfo.getmAddress() != null
     *      如果没有手动选择地址 则mKaikaYuYueOrderInfo.getmAddress() == null
     *      如果选择了地址 再去重新选择套餐 会自动获取用户的默认地址  此时默认地址跟用户选择的地址可能不一致
     * @param yuyueViewShowEnity
     */
    @Override
    public void viewSetValue(YuyueViewShowEnity yuyueViewShowEnity) {
        String adr = yuyueViewShowEnity.getAdress();
        String packageName = yuyueViewShowEnity.getPackageName();
        String telNum = yuyueViewShowEnity.getPhoneNum();
        if(!TextUtils.isEmpty(packageName)){
            mKaikaYuYueOrderInfo.setmPackageInfo(yuyueViewShowEnity.getPackageName());
            mKaikaYuYueOrderInfo.setmPackageId(yuyueViewShowEnity.getPackageIcpID());
        }
        if(!TextUtils.isEmpty(telNum)){
            mKaikaYuYueOrderInfo.setmPhoneNum(telNum);
        }
        if(TextUtils.isEmpty(mKaikaYuYueOrderInfo.getmAddress())){
            mKaikaYuYueOrderInfo.setmAddressId(yuyueViewShowEnity.getAdressID());
            mKaikaYuYueOrderInfo.setmAddress(yuyueViewShowEnity.getAdress());
        }
        mSelectAdr.setText(TextUtils.isEmpty(adr) ? "选择地址" : adr);
        mSelectPackage.setText(TextUtils.isEmpty(packageName) ? "选择套餐" : packageName);
        mSelectPhoneNum.setText(TextUtils.isEmpty(telNum) ? "选择号码" : telNum);
    }

    @Override
    public void setNewAdr(String adrName, String adrID) {
        mSelectAdr.setText(TextUtils.isEmpty(adrName) ? "选择地址" : adrName);
        mKaikaYuYueOrderInfo.setmAddress(adrName);
        mKaikaYuYueOrderInfo.setmAddressId(adrID);
    }

    @Override
    public void loadDataComplated() {
        dismissProgressDialog();
    }

    @Override
    public void loadDataError() {
        dismissProgressDialog();
        showDialog(null, getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return SubscribeKaikaMainPrecenter.create();
    }
}
